package com.zhiyou100.weather.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhiyou100.weather.pojo.WeatherResponse;
import com.zhiyou100.weather.service.IWeatherDataService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;

@Service("iWeatherDataService")
public class WeatherDataService implements IWeatherDataService {

    @Resource
    private RestTemplate restTemplate;
    private static final String url = "http://wthrcdn.etouch.cn/weather_mini?";

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = url + "citykey=" + cityId;
        return getData(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = url + "city=" + cityName;
        return getData(uri);
    }

    private WeatherResponse getData(String uri) {

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
        //解析JSON对象
        ObjectMapper objectMapper = new ObjectMapper();
        //Weather数据
        WeatherResponse weatherResponse = null;
        //JSON数据
        String body = null;
        //判断如果状态==200
        if (responseEntity.getStatusCodeValue() == 200) {
            body = responseEntity.getBody();
        }
        try {
            weatherResponse = objectMapper.readValue(body, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return weatherResponse;
    }
}
